package com.example.foodwebbackend.controller;

import com.example.foodwebbackend.dto.ApiResponse;
import com.example.foodwebbackend.service.AdminStatsService;
import com.example.foodwebbackend.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/admin/stats")
@CrossOrigin(origins = "*")
public class AdminStatsController {

    @Autowired
    private AdminStatsService adminStatsService;
    
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 获取总用户数
     */
    @GetMapping("/users")
    public ApiResponse<Integer> getTotalUsers() {
        try {
            int totalUsers = adminStatsService.getTotalUsers();
            return ApiResponse.success(totalUsers);
        } catch (Exception e) {
            return ApiResponse.error("获取用户统计失败: " + e.getMessage());
        }
    }

    /**
     * 获取总商家数
     */
    @GetMapping("/merchants")
    public ApiResponse<Integer> getTotalMerchants() {
        try {
            int totalMerchants = adminStatsService.getTotalMerchants();
            return ApiResponse.success(totalMerchants);
        } catch (Exception e) {
            return ApiResponse.error("获取商家统计失败: " + e.getMessage());
        }
    }

    /**
     * 获取总美食数
     */
    @GetMapping("/foods")
    public ApiResponse<Integer> getTotalFoods() {
        try {
            int totalFoods = adminStatsService.getTotalFoods();
            return ApiResponse.success(totalFoods);
        } catch (Exception e) {
            return ApiResponse.error("获取美食统计失败: " + e.getMessage());
        }
    }
    
    /**
     * 验证管理员token
     */
    private boolean validateAdminToken(String token) {
        try {
            if (token == null || !token.startsWith("Bearer ")) {
                return false;
            }
            
            String jwt = token.substring(7);
            String userType = jwtUtil.getUserTypeFromToken(jwt);
            return "admin".equals(userType);
        } catch (Exception e) {
            return false;
        }
    }
} 